<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Think\Controller;
use Com\DingdingAuth;
/**
 * 后台用户控制器
 * 
 * @author jry <598821125@qq.com>
 */
class TaskController extends AdminController
{
	/**
	 * 发钉
	 */
	public function sendDing(){
		$corpid=C('CORPID');
		$corpsecret=C('SECRET');
		$token = session("token");
		if (!empty($token)){
			$D=new DingdingAuth($corpid,$corpsecret,$token);
		}else{
			$D=new DingdingAuth($corpid, $corpsecret);
			$token = $D->getAccessToken();
			session(array('expire' => 7200));
			session("token", $token['access_token']);
		}
		$redirect_uri=urlencode('http://dingding.w172.126t.net/home/taskwap/index');
		$url='https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoa2vwlygt70y6eagkn&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='.$redirect_uri;
		dump($url);exit;
		$data=array(
				'touser'=>'06265805117373',
				'agentid'=>C('AGENTID'),
				'msgtype'=>'oa',
				'oa'=>array(
						'message_url'=>$url,
						'head'=>array(
								"bgcolor"=>"FFBBBBBB",
								"text"=>"好聚点科技"
						),
						'body'=>array(
								"title"=>"项目：fyt00001",
								"form"=>array (
										array(
												"key"=> "执行人：",
												"value"=>"高龙翔"
										),
										array(
												"key"=> "类型：",
												"value"=>"测试"
										),
										array(
												"key"=> "级别：",
												"value"=>"非常紧急"
										),
										
											
								),
								"content"=>"小时候不懂事，听别人说你魅力无穷，
								很多人想得到你，后来长大，慢慢懂事了，
								每次看到红扑扑的你都兴奋不已，想要把你占为己有！
								~~~亲爱的百元大钞！
								",
								//"image"=>"@lADOADmaWMzazQKA",
								//"file_count"=> "",
								"author"=>"好聚点科技"
						),
				),
		);
		 
		$re=$D->getDingRe("message/send",$data,'POST','');
		 
		dump($re);
		$messageId=$re['messageId'];
		//获取部门成员userid
// 		$param=array(
//     			"department_id"=>"",//部门id
//     	);
// 		$re=$D->getDingRe("user/simplelist",'','GET',$param);
// 			foreach ($re['userlist'] as $k=>$v){
// 				M('User')->where(array('username'=>$v['name']))->setfield('ding_id',$v['userid']);
// 			}
		 
		   
		exit;
	}
    public function index()
    {
    			
       // 搜索
		$keyword = I('keyword', '', 'string');
		$condition = array('like', '%' . $keyword . '%');
		$map['projectid|uid'] = array($condition, $condition, '_multi' => true);
		$employee_id = I('uid');
		if ($employee_id) {
			$map['uid'] =array('like', '%,' . $employee_id . ',%');
		}
		$keywords = I('keywords');
		if (!empty($keywords)) {
			$where['type'] = $keywords;
			$where['status'] = $keywords;
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
		}
		$projectid = I('projectid');
		if (!empty($projectid)) {
			$map['projectid'] = $projectid;
		}
		// 获取所有用户
		$map['status'] = array('egt', '0');
		// 禁用和正常状态
	     $data_list = D('Task')->page(! empty($_GET["p"]) ? $_GET["p"] : 1, C('ADMIN_PAGE_ROWS'))->where($map)->order('status asc,emergency_level asc,id desc')->select();
        $page = new \Common\Util\Page(D('Task')->where($map)->count(), C('ADMIN_PAGE_ROWS'));
        
        foreach ($data_list as $key => &$val) {
            $mapp['id'] = $val['projectid']; // 项目id
            $mapk['id'] = $val['uid']; // 客服id
            $project = D('Project');
            $project_name = $project->where($mapp)->field('project_name')->find(); // 项目名称
            $employee = D('Employee');
            $uid_arr=explode(',',$val['uid']);
            $uidstr=array();
            foreach ($uid_arr as $k=>$v){
            	
            	if ($v!='') {
            		$employee_name = $employee->field('name')->find($v); // 员工姓名
            		$uidstr[$k] = '<a href="'.U('Task/index',array('uid'=>$v)).'" style="text-decoration:none;">'.$employee_name['name'].'</a>';
            	}
            }
            $val['uid']=implode("|",$uidstr);
            $val['projectid'] = $project_name['project_name'];
            $kk['tablename'] = 'emergency_level';
            $kk['fieldvalue'] = $val['emergency_level'];
            $emergency_level = D('Descriptions')->where($kk)->find();
            
            $val['emergency_level'] = $emergency_level['title'];
            $ll['tablename'] = 'task_type';
            $ll['fieldvalue'] = $val['type'];
            $task_type = D('Descriptions')->where($ll)->find();
            
            if ($val['start_time']) {
                $val['start_end_time'] = date('Y/m/d', $val['start_time']) . '~';
            } else {
                $val['start_end_time'] = '---';
            }
            if ($val['end_time']) {
                $val['start_end_time'] .= date('Y/m/d', $val['end_time']);
            }
            
            $val['content'] = '<a href="' . U('Admin/Task/xq', array(
                'id' => $val['id']
            )) . '" style="text-decoration:none;">' . $val['content'] . '</a>';
            
            $val['type'] = $task_type['title'];
            if ($val['status'] == 1) {
                $val['task_status'] = 1;
            } elseif ($val['status'] == 2) {
                $val['task_status'] = 2;
            } elseif ($val['status'] == 3) {
                $val['task_status'] = 3;
            }
        }
        
        $attr['field'] = 'task_status';
        $attr[2]['title'] = '&nbsp;开&nbsp;&nbsp;始&nbsp;';
        $attr[2]['class'] = 'label label-xq';
        $attr[2]['href'] = U('Admin/task/status', array('id' => '__data_id__'));
        
        $attr['field'] = 'task_status';
        $attr[1]['title'] = '&nbsp;完&nbsp;&nbsp;成&nbsp;';
        $attr[1]['class'] = 'label label-xq';
        $attr[1]['href'] = U('Admin/task/status', array('id' => '__data_id__'));
        
        // $attrr['title'] = '任务详情';
        // $attrr['class'] = 'label label-tf';
        // $attrr['href'] = U('Admin/Task/xq', array('id' => '__data_id__'));
        $sonTask['title'] = '新增子任务';
        $sonTask['class'] = 'label label-tf';
        $sonTask['href'] = U('Admin/Task/addsontask', array('id' => '__data_id__'));
        $task_type = D('Descriptions')->where("tablename='task_type'")->select();
        $task_status = D('Descriptions')->where("tablename='task_status'")->select();
        // 使用Builder快速建立列表页面。
        $builder = new \Common\Builder\ListBuildertask();
		      $builder->setMetaTitle('项目信息列表')
		 // 设置页面标题
		->addTopButton('addnew')
		
		 // 添加新增按钮
		// ->addTopButton('resume') //添加启用按钮
		// ->addTopButton('forbid') //添加禁用按钮
		->addTopButton('delete')
		 ->addTopButton('self',array('title' => '我的任务','href' => U('Admin/task/my') )) 
		 // 添加删除按钮
		->setSearch('请输入项目ID/员工ID', U('index'), $task_type, $task_status)
		->addTableColumn('projectid', '项目')
		->addTableColumn('uid', '执行人')
		
		// ->addTableColumn('emergency_level', '紧急级别')
		->addTableColumn('content', '任务内容')
		->addTableColumn('start_end_time', '任务起止时间')
		
		// ->addTableColumn('start_time','开始时间')
		// ->addTableColumn('end_time','结束时间')
		->addTableColumn('create_time', '创建时间', 'time')
		->addTableColumn('creater', '创建人')
		->addTableColumn('type', '类型')
		
		// ->addTableColumn('status', '状态', 'status')
		->addTableColumn('right_button', '操作', 'btn')
		->setTableDataList($data_list)
		 // 数据列表
		->setTableDataPage($page->show())
		 // 数据列表分页
		->addRightButton('edit')
		 // 添加编辑按钮
		// ->addRightButton('forbid') //添加禁用/启用按钮
		// ->addRightButton('delete') //添加删除按钮
		// ->addRightButton('self',$attrr)
		      ->addRightButton('self',$sonTask)
        ->addRightButton('caseButton', '', $attr)
            ->display();
    }
    // 新增信息
    public function add()
    {
    	$corpid=C('CORPID');
    	$corpsecret=C('SECRET');
    	$D=new DingdingAuth($corpid, $corpsecret);
    	$token = $D->getAccessToken();
    	    	

        $task_type = D('Descriptions')->where('tablename="task_type"')
            ->field('fieldvalue as id,title')
            ->select();
        $emergency_level = D('Descriptions')->where('tablename="emergency_level"')
            ->field('fieldvalue as id,title')
            ->select();
//         $yuangong_arr = M("employee")->where("department>0")
//             ->field("id,name as title")
//             ->select();
        if (IS_POST) {
            //$arr_content = explode("\r\n", $_POST['content']);
           //$n = 0;
            $project_object = D('Task');
            $data = $project_object->create();
//             foreach ($arr_content as $val) {
//                 $data['content'] = $val;
//                 $data['status'] = 2;
//                 if ($project_object->add($data)) {
//                     $n ++;
//                 }
//             }
            //dump($_POST);exit;
            $uid_arr=$_POST['uid'];
            $uid_str=implode(",",$uid_arr);
            $uid_str=",".$uid_str.",";
            $data['uid']=$uid_str;
            $data['status'] = 2;
            $data['pid'] = 0;
            $data['creater'] = M('Employee')->where(array('name'=>$_POST["creater"]))->getField('id');
            $n=$project_object->add($data);
                       
            $project_number=M('Project')->where('id='.$_POST['projectid'])->getField('project_number');
           
            foreach ($_POST['uid'] as $k=>$v){
            	$name=M('Employee')->where(array('id'=>$v))->getField('name');
            	$user_name .= $name."|";
            	$ding_id=M('Employee')->where(array('id'=>$v))->getField('ding_id');
            	$touser .= $ding_id."|";
            }
            $user_name=substr($user_name,0,-1);
            $touser=substr($touser,0,-1);
            $emergency_level = M('Descriptions')->where(array('tablename'=>'emergency_level','fieldvalue'=>$_POST['emergency_level']))->getField('title');
            $type= M('Descriptions')->where(array('tablename'=>'task_type','fieldvalue'=>$_POST['type']))->getField('title');
//             $d=1;
//             foreach ($arr_content as $v){
//             	$content.=$d."：".$v;
//             	$d++;
//             }
            $content=$_POST['content'];
            $creater=$_POST['creater'];
            if ($n) {
            	//发钉钉消息
            	
            	$data=array(
            			'touser'=>"$touser",
            			'agentid'=>C('AGENTID'),
            			'msgtype'=>'oa',
            			'oa'=>array(
            					'message_url'=>'http://dingding.w172.126t.net/Wap/Task/mytask',
            					'head'=>array(
            							"bgcolor"=>"FFFF4234",
            							"text"=>"好聚点科技"
            					),
            					'body'=>array(
            							"title"=>"项目：".$project_number,
            							"form"=>array (
            									array(
            											"key"=> "执行人：",
            											"value"=>$user_name
            									),
            									array(
            											"key"=> "类型：",
            											"value"=>$type
            									),
            									array(
            											"key"=> "级别：",
            											"value"=>$emergency_level
            									),
            							),
            							"content"=>$content,
            							//"image"=>"@lADOADmaWMzazQKA",
            							//"file_count"=> "",
            							"author"=>$creater
            					),
            			),
            	);
            	
            	$re=$D->getDingRe("message/send",$data,'POST','');
            	         	
                $this->success('新增任务成功', U('index'));
            } else {
                $this->error('新增失败');
            }
        } else {
            $projectid = I('projectid');
            $project = get_project_info($projectid, 'project_number');
            $id = is_login();
            $username = get_user_info($id);
            
                                   
            // 使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('新增项目信息')
                -> // 设置页面标题
setPostUrl(U('add'))
                -> // 设置表单提交地址
addFormItem('reg_type', 'hidden', '注册方式', '注册方式')
              
             //->addFormItem('usertype', 'radio', '用户类型', '用户类型', C('USER_TYPE_LIST'))
             //->addFormItem('projectid', 'project', '项目编号', '项目ID')
           	    ->addFormItem('projectid', 'project_list', '项目编号', $project);
             	//->addFormItem('uid', 'select2', '员工ID', '员工ID', $yuangong_arr)
            $bumen_arr=M('UserGroup')->where(array('id'=>array("in","3,4,5"),"status"=>1))->select();
             
            foreach($bumen_arr as $k=>$v){
            	$yuangong_arr=M("employee")->where(array('department'=>array('eq',$v['id'])))
            	->field("id,name as title")
            	->select();
            	$yuangong_arr = arr_to_option($yuangong_arr);
            	$builder->addFormItem('uid', 'checkbox', '开发者', $v['title'], $yuangong_arr);
            	            	 
            }
                $builder
                //->addFormItem('uid', 'checkbox', '开发者', '开发者', $yuangong_arr)
                ->addFormItem('type', 'select2', '类型', '类型', $task_type)
                ->addFormItem('emergency_level', 'select2', '紧急级别', '紧急级别', $emergency_level)
                ->addFormItem('content', 'textarea', '任务内容', '任务内容')
                ->
            // ->addFormItem('start_time','date','开始时间','开始时间')
            // ->addFormItem('end_time','date','结束时间','结束时间')
            addFormItem('creater', 'text', '创建人', '创建人')
                ->
            setFormData(array(
               // 'creater' => $username['username'],
                'projectid' => $projectid
            ))
                ->display();
                 // 注册方式为后台添加

        }
    }

    public function myadd()
    {
        $task_type = D('Descriptions')->where('tablename="task_type"')
            ->field('fieldvalue as id,title')
            ->select();
        $emergency_level = D('Descriptions')->where('tablename="emergency_level"')
            ->field('fieldvalue as id,title')
            ->select();
        $yuangong_arr = M("employee")->where("department>0")
            ->field("id,name as title")
            ->select();
        if (IS_POST) {
            $arr_content = explode("\r\n", $_POST['content']);
            $n = 0;
            $project_object = D('Task');
            $data = $project_object->create();
            foreach ($arr_content as $val) {
                $data['content'] = $val;
                $data['status'] = 2;
                
                if ($project_object->add($data)) {
                    $n ++;
                }
            }
            
            if ($n) {
                $this->success('新增' . $n . '条任务', U('my'));
            } else {
                $this->error('新增失败');
            }
        } else {
            $projectid = I('projectid');
            $id = is_login();
            $eid = M("Employee")->where("uid=$id")->getField('id');
            $username = get_user_info($id);
            // 使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('新增项目信息')
                -> // 设置页面标题
setPostUrl(U('myadd'))
                -> // 设置表单提交地址
addFormItem('reg_type', 'hidden', '注册方式', '注册方式')
                ->
            // ->addFormItem('usertype', 'radio', '用户类型', '用户类型', C('USER_TYPE_LIST'))
            addFormItem('projectid', 'project', '项目编号', '项目ID')
                ->addFormItem('uid', 'select2', '员工ID', '员工ID', $yuangong_arr)
                ->addFormItem('type', 'select2', '类型', '类型', $task_type)
                ->addFormItem('emergency_level', 'select2', '紧急级别', '紧急级别', $emergency_level)
                ->addFormItem('content', 'textarea', '任务内容', '任务内容')
                ->
            // ->addFormItem('start_time','date','开始时间','开始时间')
            // ->addFormItem('end_time','date','结束时间','结束时间')
            addFormItem('creater', 'text', '创建人', '创建人')
                ->
            setFormData(array(
                'creater' => $username['username'],
                'projectid' => $projectid,
                'uid' => $eid
            ))
                -> // 注册方式为后台添加
display();
        }
    }

    /**
     * 编辑
     * 
     * @author jry <598821125@qq.com>
     */
    public function edit($id)
    {
        $task_type = D('Descriptions')->where('tablename="task_type"')
            ->field('fieldvalue as id,title')
            ->select();
        $emergency_level = D('Descriptions')->where('tablename="emergency_level"')
            ->field('fieldvalue as id,title')
            ->select();
        $yuangong_arr = M("employee")->where("department>0")
            ->field("id,name as title")
            ->select();
        // 获取信息
        $info = D('Task')->find($id);
        
        if (IS_POST) {
            $_POST['start_time'] = strtotime($_POST['start_time']);
            $project_object = D('Task');
            
            if ($project_object->save($_POST)) {
                $this->success('更新成功', U('index'));
            } else {
                $this->error('更新失败', $project_object->getError());
            }
        } else {
            $info = D('Task')->find($id);
            // 使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('编辑')
                -> // 设置页面标题
setPostUrl(U('edit'))
                -> // 设置表单提交地址
addFormItem('id', 'hidden', 'ID', 'ID')
                ->
            // ->addFormItem('usertype', 'radio', '用户类型', '用户类型', C('USER_TYPE_LIST'))
            addFormItem('projectid', 'text', '项目ID', '项目ID')
                ->addFormItem('uid', 'select2', '员工ID', '员工ID', $yuangong_arr)
                ->addFormItem('type', 'select2', '类型', '类型', $task_type)
                ->addFormItem('emergency_level', 'select2', '紧急级别', '紧急级别', $emergency_level)
                ->addFormItem('content', 'textarea', '任务内容', '任务内容')
                ->addFormItem('start_time', 'date', '开始时间', '开始时间')
                ->
            // ->addFormItem('end_time','text','结束时间','结束时间')
            addFormItem('creater', 'text', '创建人', '创建人')
                ->
            setFormData($info)
                ->display();
        }
    }

    public function myedit($id)
    {
        $task_type = D('Descriptions')->where('tablename="task_type"')
            ->field('fieldvalue as id,title')
            ->select();
        $emergency_level = D('Descriptions')->where('tablename="emergency_level"')
            ->field('fieldvalue as id,title')
            ->select();
        $yuangong_arr = M("employee")->where("department>0")
            ->field("id,name as title")
            ->select();
        // 获取信息
        $info = D('Task')->find($id);
        
        if (IS_POST) {
            $_POST['start_time'] = strtotime($_POST['start_time']);
            $project_object = D('Task');
            
            if ($project_object->save($_POST)) {
                $this->success('更新成功', U('my'));
            } else {
                $this->error('更新失败', $project_object->getError());
            }
        } else {
            
            // 使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('编辑')
                -> // 设置页面标题
setPostUrl(U('myedit'))
                -> // 设置表单提交地址
addFormItem('id', 'hidden', 'ID', 'ID')
                ->
            // ->addFormItem('usertype', 'radio', '用户类型', '用户类型', C('USER_TYPE_LIST'))
            addFormItem('projectid', 'text', '项目ID', '项目ID')
                ->addFormItem('uid', 'select2', '员工ID', '员工ID', $yuangong_arr)
                ->addFormItem('type', 'select2', '类型', '类型', $task_type)
                ->addFormItem('emergency_level', 'select2', '紧急级别', '紧急级别', $emergency_level)
                ->addFormItem('content', 'textarea', '任务内容', '任务内容')
                ->addFormItem('start_time', 'date', '开始时间', '开始时间')
                ->
            // ->addFormItem('end_time','text','结束时间','结束时间')
            addFormItem('creater', 'text', '创建人', '创建人')
                ->
            setFormData($info)
                ->display();
        }
    }

    public function my()
    {
        $uid = is_login();
        // 搜索
        if (I('projectid')) {
            $map['projectid'] = I('projectid');
        }
        $keyword = I('keyword', '', 'string');
        $condition = array(
            'like',
            '%' . $keyword . '%'
        );
        $map['projectid|uid'] = array(
            $condition,
            $condition,
            '_multi' => true
        );
        $employee = D('Employee')->where("uid='$uid'")->find();
        $where['uid'] = $employee['id'];
        $where['creater'] = $employee['name'];
        $where['_logic'] = 'or';
        $map['_complex'] = $where;
        
        $keywords = I('keywords');
        if (! empty($keywords)) {
            
            $map['_string'] = "type=$keywords or status=$keywords";
        }
        
        // $attrr['title'] = '任务详情';
        // $attrr['class'] = 'label label-tf';
        // $attrr['href'] = U('Admin/Task/xq', array('id' => '__data_id__'));
        
        // 获取所有用户
        
        $data_list = D('Task')->page(! empty($_GET["p"]) ? $_GET["p"] : 1, C('ADMIN_PAGE_ROWS'))
            ->where($map)
            ->order('status asc,emergency_level asc,id desc')
            ->select();
        $page = new \Common\Util\Page(D('Task')->where($map)->count(), C('ADMIN_PAGE_ROWS'));
        
        foreach ($data_list as $key => &$val) {
            $mapp['id'] = $val['projectid']; // 项目id
            $mapk['id'] = $val['uid']; // 客服id
            $project = D('Project');
            $project_name = $project->where($mapp)
                ->field('project_name')
                ->find(); // 项目名称
            $employee = D('Employee');
            $employee_name = $employee->where($mapk)
                ->field('name')
                ->find(); // 员工姓名
            $val['uid'] = $employee_name['name'];
            $val['projectid'] = $project_name['project_name'];
            
            $val['content'] = '<a href="' . U('Admin/Task/myxq', array(
                'id' => $val['id']
            )) . '" style="text-decoration:none;">' . $val['content'] . '</a>';
            $val['emergency_level'] = get_descriptions_title('emergency_level', '', $val['emergency_level']);
            
            if ($val['start_time']) {
                $val['start_end_time'] = date('Y/m/d', $val['start_time']) . '~';
            } else {
                $val['start_end_time'] = '---';
            }
            if ($val['end_time']) {
                $val['start_end_time'] .= date('Y/m/d', $val['end_time']);
            }
            
            $val['type'] = get_descriptions_title('task_type', '', $val['type']);
            $val['task_status'] = $val['status'];
            $val['status'] = get_descriptions_title('task_status', '', $val['status']);
        }
        $attr['field'] = 'task_status';
        $attr[2]['title'] = '&nbsp;开&nbsp;&nbsp;始&nbsp;';
        $attr[2]['class'] = 'label label-xq';
        $attr[2]['href'] = U('Admin/task/mystatus', array(
            'id' => '__data_id__'
        ));
        
        $attr['field'] = 'task_status';
        $attr[1]['title'] = '&nbsp;完&nbsp;&nbsp;成&nbsp;';
        $attr[1]['class'] = 'label label-xq';
        $attr[1]['href'] = U('Admin/task/mystatus', array(
            'id' => '__data_id__'
        ));
        
        $addnew['title'] = "新增";
        $addnew['class'] = "btn btn-primary";
        $addnew['href'] = U('Admin/Task/myadd');
        
        $task_type = D('Descriptions')->where("tablename='task_type'")->select();
        $task_status = D('Descriptions')->where("tablename='task_status'")->select();
        
        // 使用Builder快速建立列表页面。
        $builder = new \Common\Builder\ListBuildertask();
        $builder->setMetaTitle('项目信息列表')
            -> // 设置页面标题
                                             // ->addTopButton('addnew')
        addTopButton('self', $addnew)
            -> // 添加新增按钮
                                           // ->addTopButton('resume') //添加启用按钮
                                           // ->addTopButton('forbid') //添加禁用按钮
        addTopButton('delete')
        
        
        ->addTopButton('self',array('title' => '我的任务','href' => U('Admin/task/my') )) 
        //    ->addTopButton('self',array('title' => '我的服务','href' => U('Admin/customer_service/my') )) 
         //   ->addTopButton('self',array('title' => '我的项目','href' => U('Admin/project/my') )) 
        
        
        
            -> // 添加删除按钮
setSearch('请输入项目ID/员工ID', U('my'), $task_type, $task_status)
            ->addTableColumn('projectid', '项目')
            ->addTableColumn('uid', '执行人')
            ->
        // ->addTableColumn('emergency_level', '紧急级别')
        addTableColumn('content', '任务内容')
            ->addTableColumn('start_end_time', '任务起止时间')
            ->
        // ->addTableColumn('start_time','开始时间')
        // ->addTableColumn('end_time','结束时间')
        addTableColumn('create_time', '创建时间', 'time')
            ->
        // ->addTableColumn('creater','创建人')
        addTableColumn('type', '类型')
            ->addTableColumn('status', '状态', 'status')
            ->addTableColumn('right_button', '操作', 'btn')
            ->setTableDataList($data_list)
            -> // 数据列表
setTableDataPage($page->show())
            -> // 数据列表分页
addRightButton('self', array(
            'title' => '编辑',
            'class' => 'label label-primary',
            'href' => U('Admin/Task/myedit', array(
                'id' => '__data_id__'
            ))
        ))
            -> // 添加编辑按钮
                                                                                                                                                   // ->addRightButton('forbid') //添加禁用/启用按钮
                                                                                                                                                   // ->addRightButton('self',$attrr) //添加任务详情按钮
        addRightButton('caseButton', '', $attr)
            ->display();
    }

    public function status($id)
    {
        $map['id'] = $id;
        $status = D('Task')->where($map)->getField('status');
        if ($status == 2) {
            $res = D('Task')->where($map)->setField('status', '1');
            $end_time = time();
            $res = D('Task')->where($map)->setField('start_time', $end_time);
            if ($res) {
                redirect(U('Task/index'));
            }
        }
        if ($status == 1) {
            $res = D('Task')->where($map)->setField('status', '3');
            $end_time = time();
            $res = D('Task')->where($map)->setField('end_time', $end_time);
            if ($res) {
                redirect(U('Task/index'));
            }
        }
    }

    public function mystatus($id)
    {
        $map['id'] = $id;
        $status = D('Task')->where($map)->getField('status');
        if ($status == 2) {
            $res = D('Task')->where($map)->setField('status', '1');
            $end_time = time();
            $res = D('Task')->where($map)->setField('start_time', $end_time);
            if ($res) {
                redirect(U('Task/my'));
            }
        }
        if ($status == 1) {
            $res = D('Task')->where($map)->setField('status', '3');
            $end_time = time();
            $res = D('Task')->where($map)->setField('end_time', $end_time);
            if ($res) {
                redirect(U('Task/my'));
            }
        }
    }

    public function xq($id)
    {
        $map['id'] = $id;
        $data_list = D('Task')->page(! empty($_GET["p"]) ? $_GET["p"] : 1, C('ADMIN_PAGE_ROWS'))
            ->where($map)
            ->order('id desc')
            ->select();
        
        foreach ($data_list as $key => &$val) {
            $mapp['id'] = $val['projectid']; // 项目id
            $mapk['uid'] = $val['uid']; // 员工id
            $project = D('Project');
            $project_name = $project->where($mapp)
                ->field('project_name')
                ->find(); // 项目名称
            $employee = D('Employee');
            $employee_name = $employee->where($mapk)
                ->field('name')
                ->find(); // 员工姓名
            $val['uid'] = $employee_name['name'];
            $val['projectid'] = $project_name['project_name'];
            $kk['tablename'] = 'emergency_level';
            $kk['fieldvalue'] = $val['emergency_level'];
            $emergency_level = D('Descriptions')->where($kk)->find();
            
            $val['emergency_level'] = $emergency_level['title'];
            $ll['tablename'] = 'task_type';
            $ll['fieldvalue'] = $val['type'];
            $task_type = D('Descriptions')->where($ll)->find();
            
            $val['type'] = $task_type['title'];
        }
        
        $builder = new \Common\Builder\ListBuilderxq();
        $builder->setMetaTitle('任务详情')
            -> // 设置页面标题
addTableGroup('zu_one', 'id', '任务ID', '1')
            ->addTableItem('zu_one', 'projectid', '项目', '4')
            ->addTableItem('zu_one', 'uid', '员工', '4')
            ->addTableItem('zu_one', 'type', '类型', '4')
            ->addTableItem('zu_one', 'emergency_level', '紧急级别', '4')
            ->
        addTableGroup('zu_three', 'content', '任务内容', '2')
            ->setTableDataList($data_list)
            ->
        // 数据列表
        display();
    }

    public function myxq($id)
    {
        $map['id'] = $id;
        
        $data_list = D('Task')->page(! empty($_GET["p"]) ? $_GET["p"] : 1, C('ADMIN_PAGE_ROWS'))
            ->where($map)
            ->order('id desc')
            ->select();
        
        foreach ($data_list as $key => &$val) {
            $mapp['id'] = $val['projectid']; // 项目id
            $mapk['uid'] = $val['uid']; // 员工id
            $project = D('Project');
            $project_name = $project->where($mapp)
                ->field('project_name')
                ->find(); // 项目名称
            $employee = D('Employee');
            $employee_name = $employee->where($mapk)
                ->field('name')
                ->find(); // 员工姓名
            $val['uid'] = $employee_name['name'];
            $val['projectid'] = $project_name['project_name'];
            $kk['tablename'] = 'emergency_level';
            $kk['fieldvalue'] = $val['emergency_level'];
            $emergency_level = D('Descriptions')->where($kk)->find();
            
            $val['emergency_level'] = $emergency_level['title'];
            $ll['tablename'] = 'task_type';
            $ll['fieldvalue'] = $val['type'];
            $task_type = D('Descriptions')->where($ll)->find();
            
            $val['type'] = $task_type['title'];
        }
        
        $builder = new \Common\Builder\ListBuilderxq();
        $builder->setMetaTitle('任务详情')
            -> // 设置页面标题
addTableGroup('zu_one', 'id', '任务ID', '1')
            ->addTableItem('zu_one', 'projectid', '项目', '4')
            ->addTableItem('zu_one', 'uid', '员工', '4')
            ->addTableItem('zu_one', 'type', '类型', '4')
            ->addTableItem('zu_one', 'emergency_level', '紧急级别', '4')
            ->
        addTableGroup('zu_three', 'content', '任务内容', '2')
            ->setTableDataList($data_list)
            ->
        // 数据列表
        display();
    }
    
    
    
    // 新增信息
    public function addsontask()
    {
    	    	
    	$corpid=C('CORPID');
    	$corpsecret=C('SECRET');
    	$D=new DingdingAuth($corpid, $corpsecret);
    	$token = $D->getAccessToken();
    	
    	
    	$task_type = D('Descriptions')->where('tablename="task_type"')
    	->field('fieldvalue as id,title')
    	->select();
    	$emergency_level = D('Descriptions')->where('tablename="emergency_level"')
    	->field('fieldvalue as id,title')
    	->select();
//     	$yuangong_arr = M("employee")->where("department>0")
//     	->field("id,name as title")
//     	->select();
    	if (IS_POST) {
    		//dump($_POST);exit;
    		$project_object = D('Task');
    		$data = $project_object->create();
    		
    		$uid_arr=$_POST['uid'];
    		$uid_str=implode(",",$uid_arr);
    		$uid_str=",".$uid_str.",";
    		$data['uid']=$uid_str;
    		$data['status'] = 2;
    		$data['creater'] = M('Employee')->where(array('name'=>$_POST["creater"]))->getField('id');
    		$n=$project_object->add($data);
    		 
    		foreach ($_POST['uid'] as $k=>$v){
    			$name=M('Employee')->where(array('id'=>$v))->getField('name');
    			$user_name .= $name."|";
    			$ding_id=M('Employee')->where(array('id'=>$v))->getField('ding_id');
    			$touser .= $ding_id."|";
    		}
    		$user_name=substr($user_name,0,-1);
    		$touser=substr($touser,0,-1);
    		$emergency_level = M('Descriptions')->where(array('tablename'=>'emergency_level','fieldvalue'=>$_POST['emergency_level']))->getField('title');
    		$type= M('Descriptions')->where(array('tablename'=>'task_type','fieldvalue'=>$_POST['type']))->getField('title');
    		$project_number=M('Project')->where('id='.$_POST['projectid'])->getField('project_number');
    		$content=$_POST['content'];
    		$creater=$_POST['creater'];
    		if ($n) {
    			//发钉钉消息
    			$data=array(
    					'touser'=>"$touser",
    					'agentid'=>C('AGENTID'),
    					'msgtype'=>'oa',
    					'oa'=>array(
    							'message_url'=>'http://dingding.w172.126t.net/Wap/Task/mytask',
    							'head'=>array(
    									"bgcolor"=>"FFFF4234",
    									"text"=>"好聚点科技"
    							),
    							'body'=>array(
    									"title"=>$project_number."的子任务",
    									"form"=>array (
    											array(
    													"key"=> "执行人：",
    													"value"=>$user_name
    											),
    											array(
    													"key"=> "类型：",
    													"value"=>$type
    											),
    											array(
    													"key"=> "级别：",
    													"value"=>$emergency_level
    											),
    									),
    									"content"=>$content,
    									//"image"=>"@lADOADmaWMzazQKA",
    									//"file_count"=> "",
    									"author"=>$creater
    							),
    					),
    			);
    			 
    			$re=$D->getDingRe("message/send",$data,'POST','');
    			 
    			$this->success('新增任务成功', U('index'));
    		} else {
    			$this->error('新增失败');
    		}
    	} else {
    		$pid=I('id');
    		$projectid =M('Task')->where(array('id'=>$pid))->getField('projectid');
    		
    		$id = is_login();
    		$username = get_user_info($id);
    	 
    		// 使用FormBuilder快速建立表单页面。
    		$builder = new \Common\Builder\FormBuilder();
    		$builder->setMetaTitle('新增项目信息') // 设置页面标题
    		->setPostUrl(U('addsontask')) // 设置表单提交地址
    		->addFormItem('pid', 'hidden', '', '')//父任务id
    		->addFormItem('projectid', 'hidden', '', ''); // 项目id
    		$bumen_arr=M('UserGroup')->where(array('id'=>array("in","3,4,5"),"status"=>1))->select();
    		 
    		foreach($bumen_arr as $k=>$v){
    			$yuangong_arr=M("employee")->where(array('department'=>array('eq',$v['id'])))
    			->field("id,name as title")
    			->select();
    			$yuangong_arr = arr_to_option($yuangong_arr);
    			$builder->addFormItem('uid', 'checkbox', '开发者', $v['title'], $yuangong_arr);
    			 
    		}
    		$builder->addFormItem('type', 'select2', '类型', '类型', $task_type)
    		->addFormItem('emergency_level', 'select2', '紧急级别', '紧急级别', $emergency_level)
    		->addFormItem('content', 'textarea', '任务内容', '任务内容')
    		->
    		
    		addFormItem('creater', 'text', '创建人', '创建人')
    		->
    		setFormData(array(
    				//'creater' => $username['username'],
    				'projectid' => $projectid,
    				'pid' => $pid
    		))
    		->display();
    		// 注册方式为后台添加
    	
    	}
    }
    
    
    
}
